package com.ratta.supernote.plugin.sticker.lib.view.stickerList;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class GridItemDecoration extends RecyclerView.ItemDecoration {
    private final int spacingV; // 垂直间距
    private final int spacingH; // 水平间距
    private int spanCount; // 列数
    private final boolean includeEdge; // 是否包含边缘间距

    public GridItemDecoration(int spanCount, int spacingV, int spacingH, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacingV = spacingV;
        this.spacingH = spacingH;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // 获取当前 item 的 position
        int column = position % spanCount; // 计算当前 item 在第几列

        if (includeEdge) {
            // 左右边距
            outRect.left = spacingH - column * spacingH / spanCount;
            outRect.right = (column + 1) * spacingH / spanCount;
        } else {
            outRect.left = column * spacingH / spanCount;
            outRect.right = spacingH - (column + 1) * spacingH / spanCount;
        }

        // 设置上下边距
        if (position >= spanCount) {
            outRect.top = spacingV; // 只有第二行及以后才添加上边距
        }
        outRect.bottom = spacingV; // 所有 item 都有底部间距
    }

    public void setSpanCount(int spanCount) {
        this.spanCount = spanCount;
    }
}
